package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Random;

@Controller
@RequestMapping("/account")
@SessionAttributes(value={"loginAccount","cart"})
public class AccountController {
    public String code;

    @Autowired
    private AccountService accountService;

    @GetMapping("/signOnForm")
    public String signOnForm(){
        return "/account/SignonForm";
    }

    @PostMapping("/signOn")
    public String signOn(Account account, String textCode, Model model){
        account = accountService.getAccountByUsernameAndPassword(account);
        Account loginAccount;
        if(account == null){
            return "/account/SignonForm";

        }else if(!textCode.equals(code)){
            return "/account/SignonForm";

        }else{
            loginAccount = account;
            model.addAttribute("loginAccount",loginAccount);
            return "/catalog/Main";
        }
    }

    @GetMapping("/signOff")
    public String signOff(Model model,HttpSession session){

        session.removeAttribute("loginAccount");
        session.removeAttribute("cart");

        model.addAttribute("loginAccount",null);
        model.addAttribute("cart",null);
        System.out.println("ww");
        return "/catalog/Main";
    }

    @GetMapping("newAccountForm")
    public String newAccountForm(){
        return "/account/NewAccountForm";
    }

    @PostMapping("/newAccount")
    public String newAccount(Account account,String textCode,Model model){

        if(!(textCode.equals(code))){
            return "/account/NewAccountForm";

        }else{

            accountService.insertAccount(account);
            model.addAttribute("loginAccount",account);
            return "/catalog/Main";
        }
    }

    @GetMapping("/isExistAccount")
    @ResponseBody
    public String isExistAccount(String username){
        Account isExistUsername = accountService.getAccountByUsername(username);

        if(isExistUsername != null){
            return "Exist";
        }
        else{
            return "Not Exist";
        }

    }

    @GetMapping("/isRightTextCode")
    @ResponseBody
    public String isRightTextCode(String textCode){
        if(textCode.equals(code)){
            return "Right";
        }else{
            return "ErrorH";
        }
    }

    @GetMapping("/editAccountForm")
    public String editAccountForm(){
        return "/account/EditAccountForm";
    }

    @PostMapping("/editAccount")
    public String editAccount(Account account,Model model,HttpSession session){

        Account loginAccount  = (Account)session.getAttribute("loginAccount");

        account.setUsername(loginAccount.getUsername());

        if(account.getPassword().equals("")){
            account.setPassword(loginAccount.getPassword());
        }

        account.setCart(loginAccount.getCart());
        account.setOrder(loginAccount.getOrder());

        model.addAttribute("loginAccount",account);
        accountService.updateAccount(account);

        return "/catalog/Main";
    }

    @GetMapping("/AdminViewAccount")

    private String AdminViewAccount(Model model){
        ArrayList<Account> AdminaccountList = accountService.getAccountList();

        model.addAttribute("AdminaccountList",AdminaccountList);
        return "/administrator/account/AdminViewAccount";
    }

    @GetMapping("/AdminEditAccount")
    private String AdminEditAccount(Model model,String username){
        Account account = accountService.getAccountByUsername(username);
        model.addAttribute("account",account);

        return "/administrator/account/EditAccount";
    }

    @PostMapping("/AdminUpdateAccount")
    private String AdminUpdateAccount(Account account){

        accountService.updateAccount(account);
        return "redirect:/account/AdminViewAccount";
    }

    @GetMapping("/deleteAccount")
    private String deleteAccount(String username,Model model){
        Account account = accountService.getAccountByUsername(username);

        if(account == null){
            model.addAttribute("error","该用户已经被删除");
            return "/ErrorH";
        }else{
            accountService.deleteAccount(username);
        }

        return "redirect:/account/AdminViewAccount";
    }

    @GetMapping("/RecoverAccount")
    private String RecoverAccount(String username){
        accountService.recoverAccount(username);

        return "redirect:/account/AdminViewAccount";
    }

    @GetMapping("/resetPassword")
    @ResponseBody
    private String resetPassword(String username){

        System.out.println(2);

        accountService.resetPassword(username);

        //不返回什么
        return "1";
    }
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Value("${spring.mail.username}")
    private String sender;

    @GetMapping("/verCode")
    @ResponseBody
    private String verCode(String receiver){
        Account account = accountService.getAccountByEmail(receiver);

        if(account == null){
            return "error";
        }
        else{
            code = accountService.getCode(sender, mailSender, receiver);
            return code;
        }

    }
    @GetMapping("/adminVerCode")
    @ResponseBody
    private String adminVerCode(String receiver){
        Account account = accountService.getAdminAccountByEmail(receiver);

        if(account == null){
            return "error";
        }
        else{
            code = accountService.getCode(sender, mailSender, receiver);
            return code;
        }

    }

    @GetMapping("/signByEmail")
    private String signByEmail(){
        return "/account/SignByEmail";
    }

    @PostMapping("/signOnByEmail")
    private String signOnByEmail(String email,String textCode,Model model){

        if(!textCode.equals(code)){
            return "/account/SignByEmail";
        }

        Account loginAccount = accountService.getAccountByEmail(email);
        model.addAttribute("loginAccount",loginAccount);
        return "/catalog/Main";
    }

    @PostMapping("/AdminSignOn")
    private String AdminSignOn(Account account){
        Account loginAccount = accountService.getAdminAccountByUsernameAndPassword(account);

        if(loginAccount == null){
            return "/administrator/account/SignonForm";
        }
        return "/administrator/catalog/main";
    }

    @GetMapping("/AdminSignByEmail")
    private String AdminSignByEmail(){
        return "/administrator/account/SignByEmail";
    }

    @PostMapping("/adminSignOnByEmail")
    private String adminSignOnByEmail(String email,String textCode){
        if(!textCode.equals(code)){
            return "/account/SignByEmail";
        }

        return "/administrator/catalog/main";
    }

    @GetMapping("/paint")
    public void verifyCode(HttpServletResponse response) throws IOException {

        final int width = 180; // 图片宽度
        final int height = 40; // 图片高度
        final String imgType = "jpeg"; // 指定图片格式 (不是指MIME类型)
        final OutputStream output = response.getOutputStream(); // 获得可以向客户端返回图片的输出流

        code = GraphicHelper.create(width, height, imgType, output);
    }
}
class GraphicHelper{
    public static String create(final int width, final int height, final String imgType, OutputStream output) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphic = image.getGraphics();

        graphic.setColor(Color.getColor("F8F8F8"));
        graphic.fillRect(0, 0, width, height);

        Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
                Color.CYAN };
        // 在 "画板"上生成干扰线条 ( 50 是线条个数)
        for (int i = 0; i < 50; i++) {
            graphic.setColor(colors[random.nextInt(colors.length)]);
            final int x = random.nextInt(width);
            final int y = random.nextInt(height);
            final int w = random.nextInt(20);
            final int h = random.nextInt(20);
            final int signA = random.nextBoolean() ? 1 : -1;
            final int signB = random.nextBoolean() ? 1 : -1;
            graphic.drawLine(x, y, x + w * signA, y + h * signB);
        }

        // 在 "画板"上绘制字母
        graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
        for (int i = 0; i < 6; i++) {
            final int temp = random.nextInt(26) + 97;
            String s = String.valueOf((char) temp);
            sb.append(s);
            graphic.setColor(colors[random.nextInt(colors.length)]);
            graphic.drawString(s, i * (width / 6), height - (height / 3));
        }
        graphic.dispose();
        try {
            ImageIO.write(image, imgType, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
